package spitter.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import spitter.dao.SpitterRepository;
import spitter.service.SpitterUserService;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity //启用web安全性
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//    @Autowired
//    private DataSource dataSource;

    @Autowired
    private SpitterRepository spitterRepository;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//          基于内存的认证
        auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("admin").roles("USER","ADMIN");
        auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("ROLE_USER").and()
                .withUser("admin").password("admin").roles("ROLE_USER","ROLE_ADMIN");

//      基于数据库的认证
//        auth.jdbcAuthentication()
//                .dataSource(dataSource);

//        自定义基于数据库的认证
//        auth.jdbcAuthentication()
//                .dataSource(dataSource)
//                .usersByUsernameQuery("select username,password,true from t_spitter where username=?")
//                .authoritiesByUsernameQuery(
//                        "select username,'ROLE_USER' from t_spitter where username=?");
//        密码编码
//        auth.jdbcAuthentication()
//                .dataSource(dataSource)
//                .usersByUsernameQuery("select username,password,true from t_spitter where username=?")
//                .authoritiesByUsernameQuery(
//                        "select username,'ROLE_USER' from t_spitter where username=?")
//                .passwordEncoder(new StandardPasswordEncoder("53cr3t"));
//        自定义用户服务
//        auth.userDetailsService(new SpitterUserService(spitterRepository));
    }

    /**
     * 对请求进行细粒度安全控制
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/spitters/register")
                .authenticated().antMatchers(HttpMethod.POST, "/spittles/**")
                .authenticated().anyRequest().permitAll();

//        http.authorizeRequests().anyRequest().permitAll();
    }


}
